package com.dji.compose_learning

import android.graphics.Bitmap
import android.graphics.Canvas
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.activity.ComponentActivity
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.unit.dp
//import androidx.lifecycle.ViewTreeLifecycleOwner
import androidx.lifecycle.ViewTreeViewModelStoreOwner
import coil.compose.rememberImagePainter
import com.dji.compose_learning.utils.observeAsState
import com.dji.compose_learning.utils.viewModel
import com.dji.compose_learning.viewmodel.SaveViewViewModel

class SaveComposeViewActivity : ComponentActivity() {
    private var printLayout: ComposeView? = null
    private val viewModel by viewModels<SaveViewViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val contentView = window.decorView
            .findViewById<ViewGroup>(android.R.id.content)
        val frameLayout = FrameLayout(this@SaveComposeViewActivity)
        val existingComposeView = contentView.getChildAt(0) as? ComposeView

        if (existingComposeView != null) with(existingComposeView) {
            contentView.removeViewAt(0)
            contentView.addView(frameLayout,
                ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
                ))
            frameLayout.addView(existingComposeView, 0, ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            ))
            addPrintLayout(frameLayout)

            setParentCompositionContext(null)
            setContent { ContentView {
                viewModel.printType.postValue(viewModel.printType.value?:0 + 1)
                printBitmap()
            } }
        } else ComposeView(this).apply {
            setParentCompositionContext(null)
            setContent { ContentView {
                viewModel.printType.postValue(viewModel.printType.value?:0 + 1)
                printBitmap()
            } }

            val decorView = window.decorView
//            if (ViewTreeLifecycleOwner.get(decorView) == null) {
//                ViewTreeLifecycleOwner.set(decorView, this@SaveComposeViewActivity)
//            }
            if (ViewTreeViewModelStoreOwner.get(decorView) == null) {
                ViewTreeViewModelStoreOwner.set(decorView, this@SaveComposeViewActivity)
            }
//            if (ViewTreeSavedStateRegistryOwner.get(decorView) == null) {
//                ViewTreeSavedStateRegistryOwner.set(decorView, this@SaveComposeViewActivity)
//            }
            val frameLayout = FrameLayout(this@SaveComposeViewActivity)
            setContentView(frameLayout, ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            ))
            frameLayout.addView(this, 0, ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            ))
            addPrintLayout(frameLayout)
        }
    }

    //添加printlayout
    private fun addPrintLayout(frameLayout: FrameLayout) {
        printLayout = ComposeView(this)
        frameLayout.addView(printLayout, 1, ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        ))
        printLayout?.visibility = View.INVISIBLE
        printLayout?.setContent { PrintContent() }
    }

    private fun printBitmap(): Bitmap {
        printLayout?.refreshDrawableState()
        val result = Bitmap.createBitmap(
            printLayout?.width ?: 1,
            printLayout?.height ?: 1,
            Bitmap.Config.ARGB_8888)
        val canvas = Canvas(result)
        printLayout?.draw(canvas)

        return result
    }
}

@Composable
fun PrintContent() {
    val viewModel = viewModel<SaveViewViewModel>()
    val state = viewModel.printType.observeAsState(0)
    Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.primary) {
        Box(contentAlignment = Alignment.Center) {
            if (state.value == 0) {
                Box(modifier = Modifier
                    .size(100.dp)
                    .background(Color.Yellow))
            } else {
                Box(modifier = Modifier
                    .size(100.dp)
                    .background(Color.Blue))
            }
        }
    }
}

@Composable
fun ContentView(getBitmap: () -> Bitmap) {
    val bitmapState = remember {
        mutableStateOf<Bitmap?>(null)
    }
    Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
        Column {
            Text(text = "Hello this content area.", color = MaterialTheme.colorScheme.onBackground)
            Button(onClick = {
                bitmapState.value = getBitmap()
            }) {
                Text(text = "Get Print Layout")
            }
            if (bitmapState.value != null) {
                Box(modifier = Modifier.padding(10.dp)) {
                    Image(painter = rememberImagePainter(data = bitmapState.value),
                        contentDescription = "")
                }
            }
        }
    }
}















